package zkclient;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

/**
 * Created by Lenovo on 2018/11/20.
 */
public class ZkClientTest {

    private static final String CONNECT_ADDR = "10.1.66.76:2181";
    private static final int SESSION_TIMEOUT = 1000;
    private static final String PARENT_NODE = "/parent";

    public static void main(String[] args) throws  Exception{
        /*
        ZkClient zkClient = new ZkClient(CONNECT_ADDR, SESSION_TIMEOUT);
        //zkClient.createPersistent(PARENT_NODE);
        zkClient.createPersistent(PARENT_NODE + "/child", "aaa");
        //获取节点个数
        System.out.println("父节点下有" + zkClient.countChildren(PARENT_NODE) + "个子节点");
        List<String> childNodes = zkClient.getChildren(PARENT_NODE);
        for(String node : childNodes){
            System.out.println("节点名称：" + node);
            String val = zkClient.readData(PARENT_NODE + "/" + node);
            System.out.println(val);
            if(val.equals("aaa")){
                zkClient.writeData(PARENT_NODE + "/" + node, "bbb");
            }
            System.out.println(zkClient.readData(PARENT_NODE + "/" + node));
            //判断节点是否存在
            if(zkClient.exists(PARENT_NODE + "/" + node)){
                zkClient.delete(PARENT_NODE + "/" + node);
                System.out.println("节点" + node + "删除成功");
            }
        }
        */

        ZkClient zkClient = new ZkClient(CONNECT_ADDR, SESSION_TIMEOUT);
        /*
        //对父节点添加监听子节点变化（创建节点，删除节点，添加子节点）
        zkClient.subscribeChildChanges(PARENT_NODE, new IZkChildListener() {
            public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
                System.out.println("handleChildChange = " + parentPath);
                System.out.println("handleChildChange = " + currentChilds.toString());
            }
        });
        */

        //监听节点数据的变化
        zkClient.subscribeDataChanges(PARENT_NODE, new IZkDataListener() {
            public void handleDataChange(String parentPath, Object data) throws Exception {
                System.out.println("handleDataChange = " + parentPath);
                System.out.println("handleDataChange = " + data.toString());
            }
            //节点被删除
            public void handleDataDeleted(String parentPath) throws Exception {
                System.out.println("handleDataDeleted = " + parentPath);
            }
        });
        /*
        zkClient.createPersistent(PARENT_NODE);
        Thread.sleep(1000);
        zkClient.createPersistent(PARENT_NODE + "/c1", "aaa");
        Thread.sleep(1000);
        zkClient.createPersistent(PARENT_NODE + "/c2", "bbb");
        Thread.sleep(1000);
        zkClient.writeData(PARENT_NODE  + "/c1", "我是c1");
        //zkClient.writeData(PARENT_NODE + "/child", "abc");
        */

    }
}
